import re

import logging
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api.urlfetch import fetch

import models_common as models
from views_common import *
import Classifier

###########################################################################################################################
# /accounting/
# GET
def index(request):
    user = getUser()
    items = models.AccountItem.all().filter('author = ', user).order('-created_on').fetch(30)

    url_linktext, url = getLoginAndUrl(request)
    
    payload = {'items': reversed(items), 'url_linktext': url_linktext, 'url': url, 'user' : user, }
    
    return render('accounting_index.html', payload)
    
###########################################################################################################################
# /accounting/edit/
# POST
# *msgkey : key of the Message
# *message : message of the Message
def edit(request):
    msgkey = request.POST['msgkey']
    msg = models.Message.get(msgkey)
    
    if msg.author == getUser():
        message = request.POST['message']
        message = unicode(message, 'utf-8').rstrip(" \n")
        msg.message = message
        msg.put()
        
        return HttpResponse(msgkey+","+msg.markedHtmlMsg())
    else:
        return HttpResponse("error!"+"Sorry, You are not authorized to do this.")

###########################################################################################################################
# /accounting/list/
# POST
# *msgkey : key of the last Message
# *clskey : key of the Classificaiton
def list(request):
    msgkey = request.POST['msgkey']
    clskey = request.POST['clskey']
    
    user = getUser()
    msgs = models.Message.all().filter('author = ', user)
    
    if msgkey and msgkey != "None":
        lastmsg = models.Message.get(msgkey)
        if lastmsg:
            msgs = msgs.filter('created_on > ', lastmsg.created_on)
        
    if clskey and clskey != "None":
        if clskey == "notmarked":
            msgs = msgs.filter('classification = ', None)
        else:
            cls = models.Classification.get(clskey)
            if cls:
                msgs = msgs.filter('classification = ', cls)
        
    msgs = msgs.order('-created_on').fetch(10)
    
    payload = {'msgs': reversed(msgs), }
    
    return render('chat_items.html', payload)

###########################################################################################################################
